package com.weixing.mall.leaf.controller;

import com.sankuai.inf.leaf.common.Result;
import com.sankuai.inf.leaf.common.Status;
import com.weixing.mall.leaf.exception.LeafServerException;
import com.weixing.mall.leaf.exception.NoKeyException;
import com.weixing.mall.leaf.service.SegmentService;
import com.weixing.mall.leaf.service.SnowflakeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class LeafController {
    private Logger logger = LoggerFactory.getLogger(LeafController.class);
    @Autowired
    SegmentService segmentService;
    @Autowired
    SnowflakeService snowflakeService;

    @GetMapping(value = "/api/segment/get/{key}")
    public long getSegmentID(@PathVariable("key") String key) {
        return get(key, segmentService.getId(key));
    }

    @GetMapping(value = "/api/snowflake/get/{key}")
    public long getSnowflakeID(@PathVariable("key") String key) {
        return get(key, snowflakeService.getId(key));

    }

    private long get(@PathVariable("key") String key, Result id) {
        Result result;
        if (key == null || key.isEmpty()) {
            throw new NoKeyException();
        }

        result = id;
        if (result.getStatus().equals(Status.EXCEPTION)) {
            throw new LeafServerException(result.toString());
        }
        return result.getId();
    }
}
